package com.opensso.core.interceptor;

import com.opensso.domain.entity.DomainPool;
import com.opensso.domain.entity.DomainPoolState;
import com.opensso.domain.service.DomainPoolSV;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 域名拦截器，拦截请求并过滤域名，比对域名是否合法
 */
@Component
@Slf4j
public class DomainInterceptor implements HandlerInterceptor {

    //域名池子
    @Resource
    private DomainPoolSV domainPoolSV;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取域名
        String domain = this.domain(request);
        DomainPool domainPool = domainPoolSV.loadByDomain(domain);
        if (domainPool == null) {
            return false;
        }
        if (DomainPoolState.getEnum(domainPool.getState()) == DomainPoolState.Enable) {
            return true;
        }

        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }


    /**
     * 获取请求的域名
     *
     * @return 域名 如 www.aicode.io
     */
    private String domain(HttpServletRequest request) {
        int endIndex = request.getRequestURL().length() - request.getRequestURI().length() + 1;
        String domain = request.getRequestURL().substring(0, endIndex);
        domain = domain.replace("http://", "").replace("/", "");
        log.info("请求来自域名 >> " + domain);
        log.info("请求地址 >> " + request.getRequestURI());
        return domain;
    }


}